package com.xzx.helloworld;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

import java.util.Date;

/**
 * 针对数据碎片的化的第一个解决方案，
 * 就固定使用4字节的int数据进行接收，组装成完整的数据，
 * @author xinzhixuan
 * @version 1.0
 * @date 2025/10/14 18:21
 */
public class TimerClientHandlerV2 extends ChannelInboundHandlerAdapter {
    private ByteBuf buf;

    /**
     * 这种方法里面不能执行耗时的操作
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        buf = ctx.alloc().buffer(4);// 分配一个4字节的buffer
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        buf.release();
        buf = null;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("channelRead");
        ByteBuf in = (ByteBuf) msg;
        try {
            buf.writeBytes(in);
            if (buf.readableBytes() >= 4) {
                long currentTimeMillis = (buf.readUnsignedInt() - 2208988800L) * 1000L;
                System.out.println(new Date(currentTimeMillis));
            }
        } finally {
            ReferenceCountUtil.release(msg); // (2)
        }
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("exceptionCaught");
        cause.printStackTrace();
        ctx.close();
    }
}
